<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: sap<songaiping@hrbjjhh.com>
// +----------------------------------------------------------------------------

namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo 客服系统-活动报名模型
 */

class ServiceActivityJoinModel extends BaseModel {

	/**
	 * @todo 报名详情（一条）
	 * @param $activity_join_id
	 * @author sap
	 * @since 2015-9-3
	 */
	public function activityJoinShow($activity_join_id=0,$field='',$activity_id=0,$customer_id=0){
		//获取数据
		$activity_join_id = (int)$activity_join_id;
		$activity_id = (int)$activity_id;
		$customer_id = (int)$customer_id;
		if($activity_join_id == 0){
			if($activity_id == 0 || $customer_id == 0){
				$this->error = '参数丢失';
				return false;
			}
		}
		//查询
		$map = array();//查询条件初始化
		if($activity_join_id != 0){
			$map['activity_join_id'] = $activity_join_id;
		}
		if($activity_id != 0){
			$map['activity_id'] = $activity_id;
		}
		if($customer_id != 0){
			$map['customer_id'] = $customer_id;
		}
		return $this->where($map)->field($field)->find();
	}

	/**
	 * @todo 查看客户是否存在绑定人（一条）
	 * @param $activity_join_id
	 * @author sap
	 * @since 2015-9-3
	 */
	public function myCustomerShow($customer_id=0){
		//获取数据
		$customer_id = (int)$customer_id;
		if($customer_id == 0){
			$this->error = '参数丢失';
			return false;
		}
		//查询
		$map = array();//查询条件初始化
		$map['customer_id'] = $customer_id;
		return M('ServiceMyCustomer')->where($map)->find();
	}
	
	/**
	 * @todo 读service_my_customer表列表
	 * @param array $where 查询条件数组
	 * @param string $field 查询字段
	 * @param string $orderby 排序
	 * @return false|array 商户列表数组
	 * @author sap
	 */
	public function getMyCustomerList($where = array(),$field= '',$orderby='customer_id desc'){
		return M('ServiceMyCustomer')->where($where)->field($field)->order($orderby)->select();
	}
	
	/**
	 * @todo 读service_activity_join表列表
	 * @param array $where 查询条件数组
	 * @param string $field 查询字段
	 * @param string $orderby 排序
	 * @return false|array 商户列表数组
	 * @author sap
	 */
	public function getActivityJoinList($where = array(),$field= '',$orderby='activity_join_id desc'){
		return $this->where($where)->field($field)->order($orderby)->select();
	}
	
	/*---------------------------------  ------------------------------------*/

	/**
	 * @todo 按渠道读待分配客户数
	 * @param unknown $activity_id
	 * @return boolean
	 */
	public function notBindCustomerNum($activity_id=0){
		$activity_id = (int)$activity_id;
		if($activity_id == 0){
			$this->error = '参数丢失';
			return false;
		}
		$map = array();
		$map['activity_id'] = $activity_id;
		$map['bind_member_id'] = 0;
		$map['sign_channel'] = array('in','0,3,4');
		$map['is_assigned'] = 0;//0未分配过
		$map['status'] = array('gt',-1);
		return $this->where($map)->field('sign_channel,count(*) as total')->group('sign_channel')->select();
	}
	
	/**
	 * @todo 根据手机号读取座席
	 * @param string $phone 手机号中用逗号分隔
	 * @author sap
	 */
	public function getPhoneBing($phone = ''){
		//获取数据
		$phone = strip_tags($phone);//手机号
		if($phone == '' || $phone == null){
			$this->error = '参数丢失';
			return false;
		}
		//通过手机号读ID
		$phone_array = explode(',' ,$phone); //在，处分割字符串
		$customer_id = array();//返回 customer_id数组初始化
		$count_phone = count($phone_array);
		if($count_phone > 300){
		    $this->error = '手机号不得超过300个';
		    return false;
		}
		if($count_phone > 0){
			for($i=0;$i<$count_phone;$i++){
// 				if(preg_match('/^1[3-8][0-9]{9}$/', $phone_array[$i])){
				    //sap明天自己改！！！！！！！！！怎么能循环操作数据库呢？？？？
					$callback = D('Admin/Customer','Service')->getCustomerIdByMobilePhone($phone_array[$i]);
					if($callback['status'] == 1){
						$customer_id[] = (int)$callback['data']['customer_id'];
					}
// 				}
			}
		}
		if(empty($customer_id)){
			$this->error = '无使用该手机号的用户，请核实';
			return false;
		}
		//读取列表
		return $this->getMyCustomerList(array('customer_id'=>array('in',$customer_id)));
	}
	
	/**
	 * @todo 处理复选框与文本框组合提交数据（用于分配绑定中）
	 * @author sap
	 */
	private function assignNum($assign_num,$member_id){
		$assign_num = (array)$assign_num;
		$member_id = array_filter(array_unique((array)$member_id));
		if(empty($member_id)){
			$this->error = '请选择用户';
			return false;
		}
		$set_num = 0;//文本框 设置总数
		foreach ($assign_num as $key=>$val){//判断总数并去掉无用数据
			if($val[0] == '' || $val[0] == null || !in_array($key,$member_id)){
				unset ($assign_num[$key]);//释放给定的变量
			}else{
				$set_num = $set_num+(int)$val[0];//设置总数相加
			}
		}	
		if(empty($assign_num) || $set_num == 0){
			$this->error = '请选择用户并填写分配人员数量';
			return false;
		}
		$result = array();
		$result['set_num'] = $set_num;
		$result['assign_num'] = $assign_num;
		return $result;
	}
	
	/**
	 * @todo 处理数据，分配客户（用于分配绑定中）
	 * @author sap
	 */
	private function myCustomerData($assign_num=array(),$customer_id=array()){
		$assign_num = (array)$assign_num;
		$customer_id = (array)$customer_id;
		if(empty($assign_num) || empty($customer_id)){
			$this->error = '参数丢失';
			return false;	
		}
		//处理数据  ----- 待改
		$star_num = 0;$data = array();$key_i=0;
		foreach ($assign_num as $key=>$val){
			$arr = array();
			$arr = array_slice($customer_id,$star_num,$val[0]);
			$star_num = $star_num+$val[0];
			for ($i=0;$i<$val[0];$i++){
				$data[$key_i]['customer_id'] = (int)$arr[$i];
				$data[$key_i]['member_id'] = $key;
			    $data[$key_i]['create_time'] = NOW_TIME;
				$key_i++;
			}
		}
		return $data;
	}
	
	/**
	 * @todo 分配未绑定用户
	 * @author sap
	 */
	public function setBindMember($activity_id,$sign_channel,$assign_num,$member_id){
		//获取数据
		$activity_id = (int)$activity_id;
		$sign_channel = (int)$sign_channel;
		$assign_num = (array)$assign_num;
		$member_id = (array)$member_id;
		if($activity_id == 0){
			$this->error = '丢失活动ID';
			return false;
		}
		$result_assign_num = $this->assignNum($assign_num,$member_id);//处理复选框与文本框组合提交数据
		if(empty($result_assign_num)){
			$this->error = $this->getError();
			return false;
		}		
		$assign_num = $result_assign_num['assign_num'];//分配情况数组
		$set_num = $result_assign_num['set_num'];//设置总人员量
		
		//未绑定用户
		$map = array();
		$map['activity_id'] = $activity_id;
		$map['bind_member_id'] = 0;
		$map['sign_channel'] = $sign_channel;
		$map['is_assigned'] = 0;//0未分配过
		$map['status'] = array('gt',-1);
		$customer_id_list = $this->getActivityJoinList($map,'activity_join_id,customer_id');
		$customer_id = array_column($customer_id_list, customer_id);//json表，报名人ID数组
		$count_num = count($customer_id);//总数
		if($count_num == 0){
			$this->error = '请正确操作';
			return false;
		}
		if($set_num>$count_num && $set_num != 0){
			$this->error = '设置总数不能大于未分配总数';
			return false;
		}
		//根据设置总数取出相应的客户数组
		$customer_id = array_slice($customer_id,0,$set_num);
		//处理数据，取出要存入MyCustomer表中数据
		$data = $this->myCustomerData($assign_num,$customer_id);
		if(empty($data)){
			$this->error = $this->getError();
			return false;
		}
		try{
			M('ServiceMyCustomer')->insertIgnoreAddAll($data);
			$map_join = array();
			$map_join['customer_id'] = array('in',$customer_id);
			$data_join['is_assigned'] = 1;
			M('service_activity_join')->where($map_join)->save($data_join);
			return true;
		}catch (\Exception $e){
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * @todo 按座席回收重新绑定用户
	 * @author sap
	 */
	public function changeBindMember($assign_num,$member_id,$old_member_id){
		$old_member_id = (array)$old_member_id;
		if(empty($old_member_id)){
			$this->error = '参数丢失';
			return false;
		}
		$result_assign_num = $this->assignNum($assign_num,$member_id);//处理复选框与文本框组合提交数据
		if(empty($result_assign_num)){
			$this->error = $this->getError();
			return false;
		}
		$assign_num = $result_assign_num['assign_num'];//分配情况数组
		$set_num = $result_assign_num['set_num'];//设置总人员量
		//原座席绑定客户数据
		$old_my_customer = $this->getMyCustomerList(array('member_id'=>array('in',$old_member_id)));
		$customer_id = array_unique(array_column($old_my_customer, customer_id));
		$count_num = count($customer_id);//总数
		if($set_num>$count_num && $set_num != 0){
			$this->error = '设置总数不能大于未分配总数';
			return false;
		}
		//根据设置总数取出相应的客户数组
		$customer_id = array_slice($customer_id,0,$set_num);
		//处理数据，取出要存入MyCustomer表中数据
		$data = $this->myCustomerData($assign_num,$customer_id);
		if(empty($data)){
			$this->error = $this->getError();
			return false;
		}
		try{
			$map_join = array();
			$map_join['customer_id'] = array('in',$customer_id);
			M('ServiceMyCustomer')->where($map_join)->delete();
			M('ServiceMyCustomer')->insertIgnoreAddAll($data);;
			return true;
		}catch (\Exception $e){
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * @todo 根据客户改变绑定人
	 * @param unknown $assign_num
	 * @param unknown $member_id
	 * @param unknown $customer_id
	 * @author sap
	 */
	public function changeBindCustomer($assign_num,$member_id,$customer_id){
		$assign_num = (array)$assign_num;
		$member_id = (array)$member_id;
		$customer_id = (array)$customer_id;
		if(empty($customer_id)){
			$this->error = '参数丢失';
			return false;
		}
		$result_assign_num = $this->assignNum($assign_num,$member_id);//处理复选框与文本框组合提交数据
		if(empty($result_assign_num)){
			$this->error = $this->getError();
			return false;
		}
		$assign_num = $result_assign_num['assign_num'];//分配情况数组
		$set_num = $result_assign_num['set_num'];//设置总人员量
		$old_my_customer = $this->getMyCustomerList(array('customer_id'=>array('in',$customer_id)));
		$customer_id = array_unique(array_column($old_my_customer, customer_id));
		$count_num = count($customer_id);//总数
		if($set_num>$count_num && $set_num != 0){
			$this->error = '设置总数不能大于未分配总数';
			return false;
		}
		$customer_id = array_slice($customer_id,0,$set_num);//待分配用户数组
		//处理数据，取出要存入MyCustomer表中数据
		$data = $this->myCustomerData($assign_num,$customer_id);
		if(empty($data)){
			$this->error = $this->getError();
			return false;
		}
		try{
			$map_join = array();
			$map_join['customer_id'] = array('in',$customer_id);
			M('ServiceMyCustomer')->where($map_join)->delete();
			M('ServiceMyCustomer')->insertIgnoreAddAll($data);
			return true;
		}catch (\Exception $e){
			$this->error = $e->getMessage();
			return false;
		}
	}

	/**
	 * @todo 按座席回收重新绑定用户
	 * @author sap
	 * @since 2016-3-2
	 */
	public function changeVipBindMember($activity_id=0,$assign_num,$member_id,$old_member_id){
	    $old_member_id = (array)$old_member_id;
	    $activity_id = (int)$activity_id;
	    if(empty($old_member_id) || $activity_id == 0){
	        $this->error = '参数丢失';
	        return false;
	    }
	    $result_assign_num = $this->assignNum($assign_num,$member_id);//处理复选框与文本框组合提交数据
	    if(empty($result_assign_num)){
	        $this->error = $this->getError();
	        return false;
	    }
	    $assign_num = $result_assign_num['assign_num'];//分配情况数组
	    $set_num = $result_assign_num['set_num'];//设置总人员量
	    //原座席绑定VIP客户数据
	    $map = array();
	    $map['member_id'] = array('in',$old_member_id);
	    $map['activity_id'] = $activity_id;
	    $map['ticket_level'] = 1;
	    $old_my_customer = D('ServiceActivityJoinView')->where($map)->select();
	    $customer_id = array_unique(array_column($old_my_customer, customer_id));
	    $count_num = count($customer_id);//总数
	    if($set_num>$count_num && $set_num != 0){
	        $this->error = '设置总数不能大于未分配总数';
	        return false;
	    }
	    //根据设置总数取出相应的客户数组
	    $customer_id = array_slice($customer_id,0,$set_num);
	    //处理数据，取出要存入MyCustomer表中数据
	    $data = $this->myCustomerData($assign_num,$customer_id);
	    if(empty($data)){
	        $this->error = $this->getError();
	        return false;
	    }
	    try{
	        $map_join = array();
	        $map_join['customer_id'] = array('in',$customer_id);
	        M('ServiceMyCustomer')->where($map_join)->delete();
	        M('ServiceMyCustomer')->insertIgnoreAddAll($data);;
	        return true;
	    }catch (\Exception $e){
	        $this->error = $e->getMessage();
	        return false;
	    }
	}
	
	/**
	 * @todo 拉取活动报名
	 * @author sap
	 * @since 2015-9-4
	 */
	public function addAllActivityJoin($activity_id=0){
		//基础数据获取及判断
		$activity_id = (int)$activity_id;
		if($activity_id == 0){
			$this->error = '参数失丢';
			return false;
		}
		//活动信息,取偏移量
		$info = D('Admin/ServiceActivity')->activityShow($activity_id,'offset_id');
		if(empty($info)){
			$this->error = '请正确操作';
			return false;
		}
		//拉取活动下数据
		$result = D('Admin/Activity','Service')->getActivityJoinPerson($activity_id,$info['offset_id']);
		if(empty($result)){
			$this->error = '无报名数据可拉取';
			return false;
		}
		//基础数据
		$count = $result['data']['count'];//总报名人员
		$num = ceil($count/2000)-1;//还可拉取次数
		$list = $result['data']['list'];//报名数据
		$customer_ids = array_unique(array_column($list, 'customer_id'));//客户ID数组
		$generalize_member_ids = array_unique(array_column($list, 'generalize_member_id'));//推广人ID数组
		$activity_join_ids = array_unique(array_column($list, 'activity_join_id'));//报名主键ID数组
		$offset_id = max($activity_join_ids);//偏移量

		/*----------------------拉取过来数据处理-------------------------*/

		$data_my = array();//第一批原有绑定人数组，初始化
		$arr = array();//添加到my_customer表的数据，初始化
		$customer_detail = array();//客服系统用户详细信息表，写入数据，初始化
		
		//写入客服系统用户详细信息数据
		foreach ($customer_ids as $key=>$val){
			$customer_detail[]['customer_id'] = $val;
		}
		
		//原有绑定人则绑定人不变
		//根据客户ID数组读取座席ID信息（即，原有绑定人信息）
		$my_customer = $this->getMyCustomerList(array('customer_id'=>array('in',$customer_ids)));
		if(!empty($my_customer)){
			//$my_customer_arr = array('customer_id'=>'member_id','customer_id'=>'member_id');
			$my_customer_arr = array();
			foreach ($my_customer as $k=>$v){
				$my_customer_arr[$v['customer_id']] = $v['member_id'];
			}
			//摘取下来的数据$list自己遍历一次，如果customer_id在$my_customer_arr中有值，则原有推广人，
			//把原来有推广人的数据放在一个新的数组中$data_my，并删除$list本身中的元素
			foreach ($list as $key=>$val){
				if(isset($my_customer_arr[$val['customer_id']])){
					$data_my[$key] = $val;
					$data_my[$key]['bind_member_id'] = $my_customer_arr[$val['customer_id']];
					unset ($list[$key]);
				}
			}
		}

		//如：没有绑定人，若推广人在杜金部门，则推广人为绑定人；若推广人不在杜金部门，则无绑定人
		if(!empty($generalize_member_ids)){
			$service_api = D('Admin/ServiceApi')->memberIsInDepartment($generalize_member_ids,1);//在杜金部门的推广人
		}
// 		$service_api = array(0=>'1',1=>'2',2=>'3',3=>'4',4=>'5',5=>'6');
// dump($service_api);die;
		if(!empty($service_api)){
			foreach ($list as $key=>$val){
				$list[$key]['bind_member_id'] = '0';//绑定人字段初始化
				//判断推广人是否在杜金团队
				if(in_array($val['generalize_member_id'],$service_api)){
					$list[$key]['bind_member_id'] = $val['generalize_member_id'];//推广人为绑定人
					$arr[$key]['customer_id'] = $val['customer_id'];
					$arr[$key]['member_id'] = $val['generalize_member_id'];
				}
			}
		}
// 		$this->startTrans();
		if(!empty($data_my)){
			if($this->addAll(array_merge($data_my),array(),true) === false){
// 				$this->rollback();
				$this->error = '操作失败，请重试1';
				return false;
			}
		}
		if(!empty($arr)){
			if(M('ServiceMyCustomer')->addAll(array_merge($arr),array(),true) === false){
// 				$this->rollback();
				$this->error = '操作失败，请重试2';
				return false;
			}
		}
		if(!empty($list)){
			if($this->addAll(array_merge($list),array(),true) === false){
// 				$this->rollback();
				$this->error = '操作失败，请重试3';
				return false;
			}
		}
		$data_activity = array();
		$data_activity['offset_id'] = $offset_id;
		$where = array();
		$where['activity_id'] = $activity_id;
		if(D('ServiceActivity')->where($where)->save($data_activity) === false){
// 			$this->rollback();
			$this->error = '操作失败，请重试4';
			return false;
		}
		if(!empty($customer_detail)){
			if(M('ServiceCustomerDetail')->insertIgnoreAddAll(array_merge($customer_detail)) === false){
				$this->error = '操作失败，请重试5';
				return false;
			}
		}
		S('service_customer_detail',null);
// 		$this->commit();
		return $num;
	}

    /**
     * @todo 查看用户是否是VIP
     * @author sap
     * @since 2015-12-15
     */
	public function getActivityJoinCustomerShow($activity_id=0,$customer_id=0){
	    $activity_id = (int)$activity_id;
	    $customer_id = (int)$customer_id;
	    if($activity_id == 0 || $customer_id == 0){
	        $this->error = '参数丢失';
	        return false;
	    }
	    //查看本地表中是否有数据
	    $show = $this->activityJoinShow('','activity_join_id,activity_id,customer_id,ticket_level',$activity_id,$customer_id);
	    //存储过则返回本地信息，结束流程
	    if(isset($show['ticket_level']) && $show['ticket_level'] == 1){
	        return $show['ticket_level'];//返回票别，0是普通票，1是VIP
	    }
	    //根据用户ID读小马接口，传参为activity_id、customer_id，
	    //如果报过名,并且是外部数据(0,3,4)，接口返回报名信息
	    $info_res = D('Admin/Activity','Service')->serviceCheckCustomerIsJoin($activity_id,$customer_id);
	    if($info_res['status'] == 1){
	        return $info_res['data']['ticket_level'];//返回票别，0是普通票，1是VIP
	    }
        $this->error = $info_res['info'];
        return false;
	}
	
	/**
	 * @todo 查看用户是否已经报名
	 * @author sap
	 */
	public function getActivityJoinShow($activity_id=0,$phone='',$customer_id=0,$customer_name=''){
		$activity_id = (int)$activity_id;//活动ID号
		$phone = strip_tags($phone);//手机号
		$customer_id = (int)$customer_id;//报名人员ID
		$customer_name = strip_tags($customer_name);
		$data = array();//返回值初始化
		if($activity_id == 0){
			$data['status'] = 0;
			$data['info'] = '请正确操作';
			return $data;
		}
		//若有手机号，则通过小马接口读$customer_id
		//根据手机号读取用户ID
		if(preg_match('/^1[3-8][0-9]{9}$/', $phone)){
			$customer_id_result = D('Admin/Customer','Service')->getCustomerIdByMobilePhone($phone);
			if($customer_id_result['status'] == 1){
				$customer_id = (int)$customer_id_result['data']['customer_id'];
			}else{
				return $customer_id_result;
			}
		}
		if($customer_id == 0){
			$data['status'] = 0;
			$data['data'] = '查看用户ID或手机号丢失';
			return $data;//无报名信息
		}
		//查看本地表中是否有数据
		$show = $this->activityJoinShow('','activity_join_id,activity_id,customer_id,is_false,sign_channel,ticket_level,customer_level',$activity_id,$customer_id);
		//存储过则返回本地信息，结束流程
		if(!empty($show)){
			$data['status'] = 1;
			$data['data'] = $show;
			return $data;//返回报名信息
		}
		//根据用户ID读小马接口，传参为activity_id、customer_id，
		//如果报过名,并且是外部数据(0,3,4)，接口返回报名信息
		//如果没报名,返回false
		$info_res = D('Admin/Activity','Service')->serviceCheckCustomerIsJoin($activity_id,$customer_id);
		if($info_res['status'] != 1){
			return $info_res;
		}
		//没有存储则调用小马改变状态接口,返回true or false
		//true 则写入本地
		//false 则返回错误，结束流程
		$info = $info_res['data'];
		$callback = D('Admin/Activity','Service')->isServiceChange($info['activity_join_id']);
		if($callback['status'] != 1){
			return $callback;
		}
		//查看用户是否存在绑定人，有绑定人则绑定人不变
		$bind_member_id = $this->myCustomerShow($info['customer_id']);
		if(!empty($bind_member_id)){
			$info['bind_member_id'] = $bind_member_id;
		}else{
			//若无绑定人，则查看推广人是否在杜金团队
			//在，则推广人为绑定人
			//若不在，则无绑定人
			$data_my_customer = array();//存入绑定表中数据
			$department_member = D('Admin/ServiceApi')->memberIsInDepartment(array(0=>$info['generalize_member_id']),1);//在杜金部门的推广人
			if(!empty($department_member)){
				$info['bind_member_id'] = $department_member[0];
				$data_my_customer['member_id'] = $department_member[0];
				$data_my_customer['customer_id'] = $info['customer_id'];
			}
			if(!empty($data_my_customer)){
				if(M('service_my_customer')->add($data_my_customer) === false){
					\Think\Log::write('活动报名:活动系统中已经存在'.arr2str($info, ',').'失败');
					$data['status'] = 0;
					$data['info'] = 'my_customer表写入失败';
					return $data;
				}
			}
		}
		//写入客服系统主表
		if($this->add($info) === false){
			\Think\Log::write('活动报名:活动系统中已经存在,绑定表已经存在'.arr2str($info, ',').'失败');
			$data['status'] = 0;
			$data['info'] = 'join表写入失败';
			return $data;
		}
		M('ServiceCustomerDetail')->insertIgnore(array('customer_id'=>$info['customer_id'],'customer_name'=>$customer_name));
		S('service_customer_detail',null);
		$info['is_false'] = 0;
 		$data['status'] = 1;
		$data['data'] = $info;
		return $data;//返回报名信息
	}

	/**
	 * @todo 活动报名接口
	 * @author sap
	 * @since 2015-9-6
	 */
	public function getAddActivityJoin($activity_id=0,$sign_channel=0,$phone_number='',$customer_id=0,$ticket_level=0,$sale_point_id=0,$generalize_member_id=0,$customer_level=0,$customer_name=''){
		//获取信息
		$activity_id = (int)$activity_id;//活动ID号
		$join_time = NOW_TIME;//报名时间
		$sign_channel = (int)$sign_channel;//1:票点报名;2:代报名;
		$phone_number = strip_tags($phone_number);//手机号
		$customer_id = (int)$customer_id;//报名人员ID
		$ticket_level = (int)$ticket_level;//0:普通票;1:VIP
		$sale_point_id = (int)$sale_point_id;//票点id(销售网点id)
		$generalize_member_id = (int)$generalize_member_id;//推广人（员工id)
		$customer_level = (int)$customer_level;//0-无,1-A类客户,2-B类客户,3-C类客户
		$customer_name = strip_tags($customer_name);
		//基础判断
		if($activity_id == 0){
			$this->error = '用户信息错误';
			return false;
		}
		if($sign_channel != 1 && $sign_channel != 2){
			$this->error = '报名渠道信息错误';
			return false;
		}
		if(preg_match('/^1[3-8][0-9]{9}$/', $phone_number)){
			$customer_id = $phone_number;//输入手机号时，手机号就是customer_id
		}
		if($customer_id == 0 || $customer_id == '' || $customer_id == null){
			$this->error = '用户信息错误';
			return false;
		}
		if($ticket_level != 0 && $ticket_level != 1){
			$this->error = '票别信息错误';
			return false;
		}
		if($sign_channel == 1){
			if($sale_point_id == 0){
				$this->error = '票点信息错误';
				return false;
			}
		}
		if($generalize_member_id == 0){
			$generalize_member_id = UID;
		}
		if($customer_level > 3){
			$this->error = '客户类型错误';
			return false;
		}

		//调用小马报名接口
		$data_api = array();//传数初始化
		$data_api['activity_id'] = $activity_id;
		$data_api['join_time'] = $join_time;
		$data_api['sign_channel'] = $sign_channel;
		$data_api['customer_id'] = $customer_id;
		$data_api['ticket_level'] = $ticket_level;
		$data_api['generalize_member_id'] = $generalize_member_id;
		$info = D('Admin/Activity','Service')->serviceCustomerJoinActivity($data_api);
		if(empty($info)){
			$this->error = D('Admin/Activity','Service')->getError();
			return false;
		}
		//查看用户是否存在绑定人，有绑定人则绑定人不变
		$bind_member_id = $this->myCustomerShow($info['customer_id']);
		if(!empty($bind_member_id)){
			$info['bind_member_id'] = $bind_member_id;
		}else{
			//若无绑定人，则查看推广人是否在杜金团队
			//在，则推广人为绑定人
			//若不在，则无绑定人
			$department_member = D('Admin/ServiceApi')->memberIsInDepartment(array(0=>$info['generalize_member_id']),1);//在杜金部门的推广人
			if($department_member === false){
				$this->error = D('Admin/ServiceApi')->getError();
				return false;
			}
			if(!empty($department_member)){
				$info['bind_member_id'] = $department_member[0];
				$data_my_customer = array();//存入绑定表中数据
				$data_my_customer['member_id'] = $department_member[0];
				$data_my_customer['customer_id'] = $info['customer_id'];
				if(M('service_my_customer')->add($data_my_customer) === false){
					\Think\Log::write('活动报名:活动系统中已经存在'.arr2str($info, ',').'失败');
					$this->error = 'my_customer写入失败';
					return false;
				}
			}
		}
		//写入客服系统主表
		$info['sale_point_id'] = $sale_point_id;
		$info['customer_level'] = $customer_level;
		if($this->add($info) === false){
			\Think\Log::write('活动报名:活动系统中已经存在,绑定表已经存在'.arr2str($info, ',').'失败');
			$this->error = 'join表写入失败';
			return false;
		}
		M('ServiceCustomerDetail')->insertIgnore(array('customer_id'=>$info['customer_id'],'customer_name'=>$customer_name));
		//操作iweb_service_roll_call_customer这个表
		if(isset($info['bind_member_id'])){
			M('service_roll_call_customer')-> where(array('customer_id'=>$info['customer_id'],'is_bind'=>'0'))->setField(array('bind_member_id'=>$info['bind_member_id'],'is_bind'=>'1'));
		}
		S('service_customer_detail',null);
		return $info;//返回报名信息
	}

	/**
	 * @todo 普通票转化VIP票
	 * @param int $activity_id 活动ID号
	 * @param int $customer_id 客户ID号
	 * @param int $generalize_member_id 转化人ID号
	 * @param int $sale_point_id 票点ID号
	 * @author sap
	 * @author 2015-10-7
	 */
	public function changeTicketLevel($activity_id=0,$customer_id=0,$generalize_member_id=0,$sale_point_id=0){
		$activity_id = (int)$activity_id;
		$customer_id = (int)$customer_id;
		$generalize_member_id = (int)$generalize_member_id;
		$sale_point_id = (int)$sale_point_id;
		if($activity_id== 0 || $customer_id == 0 || $generalize_member_id == 0){
			$this->error = '参选丢失';
			return false;
		}
		//查看本地表中是否有数据
		$show = $this->activityJoinShow('','activity_join_id,ticket_level,is_false',$activity_id,$customer_id);
		if(empty($show)){
			$this->error = '无报名信息';
			return false;
		}
		//判断是否是VIP票
		if($show['ticket_level'] == 1){
			$this->error = '已经是VIP票，无需转化';
			return false;
		}
		
		$map = array();$data = array();//$data修改join表中的字段初始化,$map修改join表的查询条件初始化
		//如是虚报的状态时，直接改变为非虚报
		if($show['is_false'] == 1){
			$data['is_false'] = 0;
		}
		$data['generalize_member_id'] = $generalize_member_id;
		$data['is_change'] = 1;
		$data['ticket_level'] = 1;
		$data['join_time'] = NOW_TIME;
		//票点转化VIP时，修改报名类别与票点信息
		if($sale_point_id != 0){
			$data['sale_point_id'] = $sale_point_id;
			$data['sign_channel'] = 1;//1:票点报名
		}
		$map['activity_join_id'] = $show['activity_join_id'];
		if($this->where($map)->save($data) === false){
			$this->error = '转化失败，请重试';
			return false;
		}
		return true;
	}

	/**
	 * @todo 获取用户报名过的活动
	 * @author fzh<fanzhaohai@hrbjjhh.com>
	 * @since 2015-9-6
	 */
	public function getCustomerActivityJoin($customer_id){
	    $customer_id=(int)$customer_id;
	    $data=array();
	    if($customer_id==0){
	        $data['status']=0;
	        $data['info']='参数错误';
	        $this->ajaxReturn($data);
	    }
	    $field='activity_id,generalize_member_id,ticket_level,join_time,is_signin,is_order';
	    $map['customer_id']=$customer_id;
	    $customer_activity_join=M('service_activity_join')->field($field)->where($map)->select();
	    if(!empty($customer_activity_join)){
	        $data['status']=1;
	        $data['data']=$customer_activity_join;
	    }else{
	        $data['status']=0;
	        $data['info']='还没有报过任何活动';
	    }
	    $this->ajaxReturn($data);
	}

	/**
	 * @todo 已经报名普通票的转化VIP
	 * @author fzh<fanzhaohai@hrbjjhh.com>
	 * @since 2015-9-7
	 */
	public function changeActivityJoin($activity_join_id,$ticket_level=0,$customer_level=1,$sale_point_id=0){
	    if((int)$activity_join_id==0){
	        $this->error='报名id错误';
	        return false;
	    }
	    //查看 活动已经报名的 状态
	    $field='ticket_level,is_false,customer_level,customer_id,activity_id,generalize_member_id';
	    $service_activity_join=M('service_activity_join');
	    
	    $activity_join=$service_activity_join->field($field)->where(array('activity_join_id'=>$activity_join_id))->find();
        if(empty($activity_join)){
            $this->error='报名信息不存在';
            return false;
        }else{
            //初始化变量（操作日志用）
            $activity_id=$activity_join['activity_id'];
            $customer_id=$activity_join['customer_id'];
           
            
            //如果已经是VIP 只允许修改客户类别
            if($activity_join['ticket_level']==1){
                //因为票点报名没有客户类别 所以只能在修改信息时验证客户类别
                if(!in_array($customer_level, array(1,2,3))){
                    $this->error='报名类别错误';
                    return false;
                }
                $data['customer_level']=(int)$customer_level;
                if((int)$customer_level!=$activity_join['customer_level']){
                    $log_type=5;
                    $remark = '修改客户类型['.getActivityName($activity_id).']';
                }else{
                    $remark=false;
                }
            }else{
                //如果为普通票 时可以转化VIP

                //执行转化操作
                if((int)$ticket_level==1){
                    //如是虚报的状态时，直接改变为非虚报
                    if($activity_join['is_false']==1){
                        $data['is_false']=0;
                    }
                    $data['generalize_member_id']=UID;
                    $data['is_change']=1;
                    $data['ticket_level']=1;
                    $data['change_time']=NOW_TIME;
                    
                    //如果为票点时更新票点， 并更改报名渠道
                    if((int)$sale_point_id!=0){
                        $data['sale_point_id']=$sale_point_id;
                        $data['sign_channel']=1;
                    }
                    $remark = '转化VIP['.getActivityName($activity_id).']';
                    $log_type=9;
                    
                }else{
                    //如果不转化VIP时 只修改客户类别
                    if(!in_array($customer_level, array(1,2,3))){
                        $this->error='报名类别错误';
                        return false;
                    }
                    $data['customer_level']=(int)$customer_level;
                    
                    if((int)$customer_level!=$activity_join['customer_level']){
                        $remark = '修改客户类型['.getActivityName($activity_id).']';
                        $log_type=5;
                    }else{
                        $remark = false;
                    }
                }
            }
            
            $return = $service_activity_join->where(array('activity_join_id'=>$activity_join_id))->save($data);
            if(false === $return){
                $this->error='失败，请重试';
                return false;
            }else{
                action_log('activityJoin_change', 'ServiceActivityJoin', $return, UID);
                //保存操作日志
                if($remark){
                    D('ServiceApi')->operationLog($customer_id,$log_type,$remark);
                }
                // 填写转化日志 customer_id:用户id,generalize_member_id:推广人id,change_member_id:转化人id,create_time
                if($log_type == 9){ // 9-活动的转化
                    $this->changeLog($activity_id, $customer_id, $activity_join['generalize_member_id'], UID);
                }
                return true;
            }
        }
	}
	
	/**
	 * @todo   转化日志
	 * @param  customer_id:用户id,generalize_member_id:推广人id,change_member_id:转化人id
	 * @return bool
	 */
	public function changeLog($activity_id, $customer_id, $generalize_member_id, $change_member_id){

	    if($activity_id == 0 || $customer_id == 0 || $generalize_member_id == 0 || $change_member_id == 0){
	        return false;
	    }
	    $data = array(
	        'activity_id' => (int)$activity_id,
	        'customer_id' => (int)$customer_id,
	        'generalize_member_id' => (int)$generalize_member_id,
	        'change_member_id' => (int)$change_member_id,
	        'create_time' => NOW_TIME,
	    );
	    $log_add = M('service_change_log')->add($data);
	    return ($log_add)? true : false ;
	}

}

